package com.lntea.jdbc.jdk;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcQueryDemo {

	public static void main(String[] args) {
		try {
			// 装载驱动
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		// 数据库连接
		Connection conn = null;
		// sql执行对象
		Statement statement = null;
		// 结果集
		ResultSet resultSet = null;
		
		try {
			// 获取mysql数据库连接
			conn = DriverManager.getConnection("jdbc:mysql://192.168.1.160:3306/lichao", "wms_dev", "OL2kfZ4s");
			// 创建sql执行对象
			statement = conn.createStatement();
			// 执行sql，返回结果集
			resultSet = statement.executeQuery("select * from user");
			// 遍历结果集，获取数据
			while(resultSet.next()){
				Long id = resultSet.getLong("id");
				String name = resultSet.getString("name");
				Integer age = resultSet.getInt("age");
				System.out.println("User[id=" + id + ",name=" + name + ",age=" + age + "]");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 关闭各种资源
			if(resultSet!=null)
				try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			if(statement!=null)
				try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			if(conn!=null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
	}
}
